package com.ruoyi.paint.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.paint.admin.domain.*;
import com.ruoyi.paint.admin.domain.Dto.CarColorSchemeDTO;
import com.ruoyi.paint.admin.domain.Dto.CarInfo;
import com.ruoyi.paint.admin.mapper.TqCarsMapper;
import com.ruoyi.paint.admin.mapper.TqColorschemesMapper;
import com.ruoyi.paint.admin.mapper.TqSchemetintsMapper;
import com.ruoyi.paint.admin.mapper.TqTintsMapper;
import com.ruoyi.paint.admin.service.ITqCarsService;
import com.ruoyi.paint.admin.service.TqColorschemesService;
import com.ruoyi.paint.admin.service.TqSchemetintsService;
import com.ruoyi.paint.admin.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 汽车信息Service业务层处理
 *
 * @author itchen
 * 2024-07-01
 */
@Slf4j
@Service
public class TqCarsServiceImpl extends ServiceImpl<TqCarsMapper, TqCars>
        implements ITqCarsService {

    @Autowired
    private TqCarsMapper tqCarsMapper;

    @Autowired
    private TqColorschemesMapper colorschemesMapper;
    @Autowired
    private TqSchemetintsMapper schemeTintsMapper;
    @Autowired
    private TqTintsMapper tqTintsMapper;
    @Autowired
    private TqColorschemesService tqColorschemesService;
    @Autowired
    private TqSchemetintsService tqSchemetintsService;

    /**
     * 查询汽车信息
     *
     * @param id 汽车信息主键
     * @return 汽车信息
     */
    @Override
    public TqCars selectTqCarsById(Long id) {
        return tqCarsMapper.selectTqCarsById(id);
    }

    /**
     * 查询汽车信息列表
     *
     * @param tqCars 汽车信息
     * @return 汽车信息
     */
    @Override
    public List<TqCarsInfo> selectTqCarsList(TqCarsInfo tqCars) {
        return tqCarsMapper.selectTqCarsList(tqCars);
    }

    @Override
    public List<TqCarsInfo> selectTqCarsListAdmin(TqCarsInfo tqCars) {
        return tqCarsMapper.selectTqCarsListAdmin(tqCars);
    }

    /**
     * 新增汽车信息
     *
     * @param tqCars 汽车信息
     * @return 结果
     */
    @Override
    public int insertTqCars(TqCars tqCars) {
        tqCars.setCreateTime(DateUtils.getNowDate());
        return tqCarsMapper.insertTqCars(tqCars);
    }

    /**
     * 修改汽车信息
     *
     * @param tqCars 汽车信息
     * @return 结果
     */
    @Override
    public int updateTqCars(TqCars tqCars) {
        tqCars.setUpdateTime(DateUtils.getNowDate());
        return tqCarsMapper.updateTqCars(tqCars);
    }

    /**
     * 批量删除汽车信息
     *
     * @param ids 需要删除的汽车信息主键
     * @return 结果
     */
    @Override
    public int deleteTqCarsByIds(Long[] ids) {
        return tqCarsMapper.deleteTqCarsByIds(ids);
    }

    /**
     * 删除汽车信息信息
     *
     * @param id 汽车信息主键
     * @return 结果
     */
    @Override
    public int deleteTqCarsById(Long id) {
        return tqCarsMapper.deleteTqCarsById(id);
    }

    @Override
    public List<TqCarsDto> selectALLsList(TqCarVo tqCars) {
        return tqCarsMapper.selectALLsList(tqCars);
    }


    @Override
    @Transactional
    public String insertTqCarsAll(CarColorSchemeDTO carColorSchemeDTO) {
        // 1. 插入Car信息
        CarInfo carInfo = carColorSchemeDTO.getCarInfo();
        LambdaQueryWrapper<TqCars> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TqCars::getBrand, carInfo.getBrand())
                .eq(TqCars::getModel, carInfo.getModel())
                .eq(TqCars::getColorName, carInfo.getColorName())
                .eq(TqCars::getPaintBrand, carInfo.getPaintBrand())
                .eq(StringUtils.isNotBlank(carInfo.getYear()),TqCars::getYear, carInfo.getYear());
        if (tqCarsMapper.selectOne(wrapper) != null) {
            return "本款车辆已存在";
        }
        TqCars tqCars = BeanCopyUtils.copyBean(carInfo, TqCars.class);
        tqCarsMapper.insert(tqCars);
        Long carId = tqCars.getId();

        // 2. 遍历colorSchemeDetails，插入ColorSchemes和关联的SchemeTints
        for (ColorSchemeDetail detail : carColorSchemeDTO.getColorSchemeDetails()) {
            LambdaQueryWrapper<TqColorschemes> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(TqColorschemes::getCarId, carId).eq(TqColorschemes::getTitle, detail.getTitle());
            if (colorschemesMapper.selectList(wrapper1).isEmpty()) {
                TqColorschemes colorScheme = new TqColorschemes();
                colorScheme.setCarId(carId);
                colorScheme.setTitle(detail.getTitle());
                if (detail.getTitle().equals("配色方案一")) {
                    colorScheme.setRemark(detail.getRemark1());
                } else if (detail.getTitle().equals("配色方案二")) {
                    colorScheme.setRemark(detail.getRemark1());
                }
                colorScheme.setOriginalColorCode(tqCars.getOriginalColorCode()); // 或其他逻辑
                colorschemesMapper.insert(colorScheme);
                Long schemeId = colorScheme.getId();
                Double surfaceTotal = detail.getSurfaceTotal();
                Double bottomTotal = detail.getBottomTotal();
                // 2.2 插入底层和面层的SchemeTints
                processTints(detail.getBottomDetails(), schemeId, bottomTotal, "底层");
                processTints(detail.getSurfaceDetails(), schemeId, surfaceTotal, "面层");
            }
        }
        return "添加成功";

    }

    private void processTints(List<ColorDetail> tintDetails, Long schemeId, Double total, String layerType) {
        if (tintDetails != null && !tintDetails.isEmpty()) {
            for (ColorDetail tintDetail : tintDetails) {
                TqTints existingTint = tqTintsMapper.selectOne(new LambdaQueryWrapper<TqTints>()
                        .eq(TqTints::getTintCode, tintDetail.getCode())
                        .eq(TqTints::getTintName, tintDetail.getName()));
                Long tqTintId;
                if (existingTint == null) {
                    TqTints tqTint = new TqTints();
                    tqTint.setTintCode(tintDetail.getCode());
                    tqTint.setTintName(tintDetail.getName());
                    tqTintsMapper.insert(tqTint);
                    tqTintId = tqTint.getId();
                } else {
                    tqTintId = existingTint.getId();
                }

                TqSchemetints schemeTint = new TqSchemetints();
                schemeTint.setSchemeId(schemeId);
                schemeTint.setTintId(tqTintId);
                schemeTint.setLayerType(layerType);
                schemeTint.setNetWeight(tintDetail.getWeight());
                schemeTint.setTotal(total);
                schemeTintsMapper.insert(schemeTint);
            }
        }
    }


//    public StringBuilder saveBatchCar(List<TqCars> collectedCar, MultipartFile file) throws IOException {
//        if (collectedCar == null || collectedCar.isEmpty()) {
//            throw new ServiceException("导入用户数据不能为空！");
//        }
//        int successNum = 0;
//        int failureNum = 0;
//        StringBuilder successMsg = new StringBuilder();
//        StringBuilder failureMsg = new StringBuilder();
//        List<Long> carIds = new ArrayList<>();
//
//        for (TqCars tqCars : collectedCar) {
//            // 检查品牌、型号和颜色名称是否为空
//            boolean hasError = false;
//            if (StringUtils.isBlank(tqCars.getBrand())) {
//                failureNum++;
//                String msg = "<br/>".concat(String.valueOf(failureNum)).concat("、车辆导入失败：品牌为空");
//                failureMsg.append(msg);
//                log.error(msg);
//                hasError = true;
//            }
//            if (StringUtils.isBlank(tqCars.getModel())) {
//                failureNum++;
//                String msg = "<br/>".concat(String.valueOf(failureNum)).concat("、车辆导入失败：型号为空");
//                failureMsg.append(msg);
//                log.error(msg);
//                hasError = true;
//            }
//            if (StringUtils.isBlank(tqCars.getColorName())) {
//                failureNum++;
//                String msg = "<br/>".concat(String.valueOf(failureNum)).concat("、车辆导入失败：颜色名称为空");
//                failureMsg.append(msg);
//                log.error(msg);
//                hasError = true;
//            }
//
//            if (tqCars.getYear() == null) {
//                failureNum++;
//                String msg = "<br/>".concat(String.valueOf(failureNum)).concat("、车辆导入失败：年款为空");
//                failureMsg.append(msg);
//                log.error(msg);
//                hasError = true;
//            }
//
//            if (StringUtils.isBlank(tqCars.getPaintBrand())) {
//                failureNum++;
//                String msg = "<br/>".concat(String.valueOf(failureNum)).concat("、车辆导入失败：油漆名称为空");
//                failureMsg.append(msg);
//                log.error(msg);
//                hasError = true;
//            }
//
//            if (hasError) {
//                throw new ServiceException("导入用户数据不能为空！"+ failureMsg);
//            }
//
//            LambdaQueryWrapper<TqCars> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(TqCars::getBrand, tqCars.getBrand())
//                    .eq(TqCars::getModel, tqCars.getModel())
//                    .eq(TqCars::getColorName, tqCars.getColorName())
//                    .eq(TqCars::getYear, tqCars.getYear())
//                    .eq(TqCars::getPaintBrand, tqCars.getPaintBrand());
//            TqCars existingCar = tqCarsMapper.selectOne(wrapper);
//            if (existingCar == null) {
//                tqCarsMapper.insert(tqCars);
//                Long id = tqCars.getId();
//                carIds.add(id);
//                successNum++;
//            } else {
//                failureMsg.append("<br/>").append("本款车辆（").append(tqCars.getBrand()).append(" ")
//                        .append(tqCars.getModel()).append(" ").append(tqCars.getColorName()).append(tqCars.getPaintBrand())
//                        .append(tqCars.getYear()).append("）已存在");
//                throw new ServiceException("本款车辆（" + tqCars.getBrand() +  tqCars.getModel() +
//                        tqCars.getColorName() + tqCars.getPaintBrand() + tqCars.getYear() +"）已存在");
//            }
//            successMsg.insert(0, "数据已全部导入成功！共 ".concat(String.valueOf(successNum)).concat(" 条，数据如下："));
//        }
//        return successMsg;
//    }

    public int saveBatchCar(List<TqCars> collectedCar, MultipartFile file) throws IOException {
        if (collectedCar == null || collectedCar.isEmpty()) {
            throw new ServiceException("导入数据不能为空！");
        }

        List<TqCars> carsToInsert = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();
        List<Long> carIds = new ArrayList<>();
        int successNum = 0;
        int failureNum = 0;

        // 遍历收集的车辆数据，检查并准备插入的数据
        for (TqCars tqCars : collectedCar) {
            // 检查品牌、型号和颜色名称是否为空
            if (StringUtils.isBlank(tqCars.getBrand()) ||
                    StringUtils.isBlank(tqCars.getModel()) ||
                    StringUtils.isBlank(tqCars.getColorName()) ||
//                    tqCars.getYear() == null ||
                    StringUtils.isBlank(tqCars.getPaintBrand())) {
                failureNum++;
                errorMessages.add("、车辆导入失败：");
                if (StringUtils.isBlank(tqCars.getBrand())) errorMessages.add("品牌为空");
                if (StringUtils.isBlank(tqCars.getModel())) errorMessages.add("型号为空");
                if (StringUtils.isBlank(tqCars.getColorName())) errorMessages.add("颜色名称为空");
//                if (tqCars.getYear() == null) errorMessages.add("年款为空");
                if (StringUtils.isBlank(tqCars.getPaintBrand())) errorMessages.add("油漆名称为空");
                log.error(errorMessages.toString());
                continue;
            }

            LambdaQueryWrapper<TqCars> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TqCars::getBrand, tqCars.getBrand())
                    .eq(TqCars::getModel, tqCars.getModel())
                    .eq(TqCars::getColorName, tqCars.getColorName())
                    .eq(StringUtils.isNotBlank(tqCars.getYear()),TqCars::getYear, tqCars.getYear())
                    .eq(TqCars::getPaintBrand, tqCars.getPaintBrand());
            List<TqCars> tqCars1 = tqCarsMapper.selectList(wrapper);

            if (! tqCars1.isEmpty()) {
                failureNum++;
                errorMessages.add("<br/>".concat(String.valueOf(failureNum)).concat("、车辆已存在"));
                continue;
            }

            carsToInsert.add(tqCars);
        }




        long startTime2 = System.currentTimeMillis();
        if (!carsToInsert.isEmpty()) {
            boolean isInsertSuccess = saveBatch(carsToInsert);
            if (isInsertSuccess) {
                successNum = carsToInsert.size();
                carIds.addAll(carsToInsert.stream().map(TqCars::getId).collect(Collectors.toList()));
            } else {
                failureNum += carsToInsert.size();
                errorMessages.add("<br/>批量插入失败");
            }
        }



        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        if (!errorMessages.isEmpty()) {
            failureMsg.append(String.join("", errorMessages));
        }
        if (failureNum > 0) {
            throw new ServiceException("部分数据导入失败：" + failureMsg);
        }
        return successNum;
    }


    @Override
    public void removeAll(List<Long> ids) {
        // 查询配色信息
        removeBatchByIds(ids);
        LambdaQueryWrapper<TqColorschemes> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TqColorschemes::getCarId, ids);
        List<TqColorschemes> list = colorschemesMapper.selectList(wrapper);
        List<Long> colorschemeIds = list.stream().map(TqColorschemes::getId).collect(Collectors.toList());
        //删除配色信息
        tqColorschemesService.removeBatchByIds(colorschemeIds);
        //删除关联信息
        LambdaQueryWrapper<TqSchemetints> wrappers = new LambdaQueryWrapper<>();
        wrappers.in(TqSchemetints::getSchemeId, colorschemeIds);
        tqSchemetintsService.remove(wrappers);
    }

    @Override
    public List<TqCarsDto> selectCarsList(TqCarVo tqCars) {
        return tqCarsMapper.selectCarsList(tqCars);
    }

    @Override
    public List<TqCarsInfo> listByparam(String param) {
        return tqCarsMapper.listByparam(param);
    }


}
